<?php
/* 这里是核心的调度功能
 * 此脚本负责:
 *  1. 处理用户传过来的参数
 *  2. 调用控制器
 *  3. 送出视图渲染结果
 */
use lightblog\engine\db;

class lightblog {
    var $request;
    var $response;
    static $app;

    function __construct($config) {
        self::$app = $this;
        $this->request = new \stdClass();
        $this->response = new \stdClass();
        $this->config = $config;

        $this->request->route = isset($_GET['r']) ? $_GET['r'] : 'home/index/index';
        $this->request->parameter = $this->getRequrstParameter();
    }

    function run() {
        $this->response->out = $this->callUserFunc();
    }

    function callUserFunc() {
        // 分解ROUTE, 找到请求的控制器以及对应的方法
        $route = explode('/', $this->request->route);

        try {
            $route_parts = count($route);
            if ($route_parts != 3 && $route_parts != 2)
                throw new \Exception("路由({$this->request->route})无法解析");
        } catch (\Exception $e) {
            exception_error($e);
        }

        if (count($route) == 3) {
            $this->request->module = $route[0];
            $this->request->controller = $route[1];
            $this->request->action = $route[2];
        }

        if (count($route) == 2) {
            $this->request->module = 'home';
            $this->request->controller = $route[0];
            $this->request->action = $route[1];
        }

        // 调用相应的控制器
        $mname = name_convert($this->request->module);
        $cname = name_convert($this->request->controller);
        $aname = name_convert($this->request->action);
        $controller_name = "lightblog\\$mname\controller\\$cname";
        try {
            if (!class_exists($controller_name, true)) {
                throw new \Exception("控制器($controller_name)不存在");
            }
            
            $controller = new $controller_name();
            $action = $aname . "Action";

            if (!method_exists($controller, $action)) {
                throw new \Exception("方法({$controller_name}->{$action})不存在");
            }
        } catch (\Exception $e) {
            exception_error($e);
        }
        return call_user_func(array($controller, $action));
    }

    /* 这个函数用来过滤用户输入, 提高安全性
     * TODO: 为了简单起见, 现在先不处理用户输入.
     * 等功能都有了再回来处理.
     */
    function getRequrstParameter() {
        $parameter = new \stdClass();
        $get = array();
        $post = array();

        $parameter->get = strip_input($_GET);
        $parameter->post = strip_input($_POST);

        $this->request->method = $_SERVER['REQUEST_METHOD'];

        return $parameter;
    }

    public function __get($key) {
        //数据库在需要的时候才加载
        if ($key == 'db') {
            $this->db = $this->db ? : new db;
        }

        return $this->$key;
    }

    public function __set($key, $value) {
        $this->$key = $value;
    }
}
